package com.tongyi.lizhishop.managers;


import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.tongyi.lizhishop.interceptors.HttpLoggingInterceptor;
import com.tongyi.lizhishop.interceptors.NetWorkInterceptor;

import com.tongyi.lizhishop.common.JsonConverterFactory;

import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit 的服务管理器
 * Created by  on 2017/8/30.
 */

public class APIServiceManager {

    public static String server_address = "http://app.lizhigongying.com";
    private static OkHttpClient client;
    private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create();

    static {
        client = new OkHttpClient().newBuilder()
                .addInterceptor(new HttpLoggingInterceptor())//添加日志拦截器
                .build();
    }

    private static Retrofit retrofit;

    /**
     * 创建retrofit服务
     *
     * @param classz
     * @param <T>
     * @return
     */
    public static <T> T createRetrofitServer(Class<T> classz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(server_address)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JsonConverterFactory.create())
                .build();
        return retrofit.create(classz);
    }

    public static Retrofit getInstance() {
        if (retrofit == null) {
             retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(server_address)
                    .addConverterFactory(gsonConverterFactory)
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .build();
        }
        return retrofit;
    }
}
